import Vue from "vue";
import VueRouter from "vue-router";
import Main from "../views/Main.vue";
import Login from "../views/Login/Login.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Main",
    component: Main,
    children: [
      {
        path: "/",
        name: "home",
        component: () => import("../views/Home/index.vue"),
      },
      {
        path: "/goods",
        name: "goods",
        component: () => import("../views/Goods/index.vue"),
      },
      {
        path: "/goods-add",
        name: "goods-add",
        component: () => import("../views/Goods/AddGoods.vue"),
      },
      {
        path: "/params",
        name: "params",
        component: () => import("../views/Params/index.vue"),
      },
      {
        path: "/advert",
        name: "advert",
        component: () => import("../views/Advert/index.vue"),
      },
      {
        path: "/user",
        name: "user",
        component: () => import("../views/User/index.vue"),
      },
    ],
  },

  {
    path: "/login",
    name: "Login",
    component: Login,
  },

  {
    path: "/register",
    name: "Login",
    component: () => import("../views/Register/index.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 路由守卫
import jwt_decode from "jwt-decode";
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.mytoken ? true : false;

  if (isLogin) {
    const decode = jwt_decode(localStorage.mytoken);
    const date = parseInt(new Date().getTime() / 1000);
    if (date - decode.iat > decode.exp - decode.iat) {
      localStorage.removeItem("mytoken");
      next("/login");
    }
  }

  if (to.path == "/login" || to.path == "/register") {
    next();
  } else {
    isLogin ? next() : next("/login");
  }
});

export default router;
